// 这个文件专门用来存放关于社区的所有接口

const residential = require('koa-router')()
const db = require("../util/db")
const fs = require('fs')
const path = require('path')
const multer = require('koa-multer')

// https://api.lzjlw.top:3456/residential/community
residential.get("/community", async (ctx) => {
    let selectSql = `select dynamicId,user.userId,userName,head_Photo,content,public_Time,type,imgUrl,islike_dynamic
    from community,user where community.userId=user.userId`
    let res = await new Promise((resolve, reject) => {
        db.query(selectSql, (err, result) => {
            if (err) {
                throw err
            } else {
                resolve(result)
            }
        })
    })
    res.sort((a,b)=>{
        return a.public_Time>b.public_Time ? 1 : -1
    })
    ctx.body = res
})


// https://api.lzjlw.top:3456/residential/community_Comments?dynamicId=${dynamicId}
residential.get("/community_Comments", async (ctx) => {
    let obj = ctx.query
    console.log(obj)
    var dynamicId = obj.dynamicId
    let selectSql = `select community_Comments.userId,head_Photo,dynamicId,commentId,userName,content,public_Time,type,islike_comment from community_Comments,user 
    where dynamicId=${dynamicId} and community_Comments.userId=user.userId`
    let res = await new Promise((resolve, reject) => {
        db.query(selectSql, (err, result) => {
            if (err) {
                throw err
            } else {
                resolve(result)
            }
        })
    })
    ctx.body = res
})


// https://api.lzjlw.top:3456/residential/community_Like?type=3 && from_Id=${dynamicId} && userId=${userId}
residential.get('/community_Like', async (ctx) => {
    let obj = ctx.query
    // 利用正则表达式去除空格
    let str = JSON.stringify(obj).toString().replace(/\s*/g, "")
    newObj = JSON.parse(str)
    console.log(newObj.type)
    let selectSql
    // 通过type值判断点赞的内容是动态还是动态评论
    // 如果是点赞的是动态，则将动态表和点赞表连接
    if (newObj.type == 3) {
        selectSql = `select * from community_Like,community 
        where community_Like.type=${newObj.type} and from_Id=${newObj.from_Id} and 
        community_Like.userId='${newObj.userId}' and community.dynamicId=community_Like.from_Id`
    }
    // 如果是点赞的是动态评论，则将动态评论表和点赞表连接
    else if (newObj.type == 4) {
        selectSql = `select * from community_Like,community_Comments 
        where community_Like.type=${newObj.type} and from_Id=${newObj.from_Id} and 
        community_Like.userId='${newObj.userId}' and community_Comments.commentId=community_Like.from_Id`
    }
    let res = await new Promise((resolve, reject) => {
        db.query(selectSql, (err, result) => {
            if (err) {
                throw err
            } else {
                if (result.length == 0) {
                    resolve(false)
                }
                else {
                    resolve(true)
                }
            }
        })
    })

    ctx.body = res
})


// https://api.lzjlw.top:3030/residential/community_Like?type=4
residential.post('/community_Like', async (ctx) => {
    let type = ctx.query.type
    let obj = ctx.request.body
    let insertSql = `insert into community_Like(userId,type,from_Id) 
    values('${obj.userId}',${type},${obj.from_Id})`
    console.log(insertSql)
    let res = await new Promise((resolve, reject) => {
        db.query(insertSql, (err, data) => {
            if (err) {
                throw err
            } else {
                resolve('insert success')
            }
        })
    })
    ctx.body = res
})


// 上传图片功能代码
residential.post('/upload', async (ctx) => {
    console.log(ctx.request.files.image)
    const img = ctx.request.files.image
    console.log('img:',img)
    console.log('图片名字：',img.name)
    const reader = fs.createReadStream(img.path)
    const imgPath = path.join(__dirname, '../public/icon/dynamicImg/' + img.name)
    const writable = fs.createWriteStream(imgPath)
    reader.pipe(writable)
    //返回图片路径
    ctx.body = '/icon/dynamicImg/' + img.name
})

// 插入动态
// https://api.lzjlw.top:3030/residential/community_dynamic?type=3
residential.post('/community_dynamic', async (ctx) => {
    const type = ctx.query.type
    let dynamicId = Math.floor((Math.random() * 1000000))
    let commentId = Math.floor((Math.random() * 1000000))
    let obj = ctx.request.body
    let time = new Date().getTime()
    if (type == 3) {
        let insertSql = `insert into community(dynamicId,userId,content,public_Time,type,imgUrl,islike_dynamic) 
        values(${dynamicId},'${obj.userId}','${obj.content}',${time},${type},'${obj.imgUrl}','false')`
        await new Promise((resolve, reject) => {
            db.query(insertSql, (err, result) => {
                if (err) {
                    console.log(err)
                }
                else {
                    resolve('insert success')
                }
            })
        })
        var dynamic = {
            dynamicId: dynamicId,
            public_Time: time
        }
        ctx.body = dynamic
    } else if (type == 4) {
        let insertSql = `insert into community_Comments(commentId,userId,dynamicId,content,public_Time,type,islike_comment) 
        values(${commentId},'${obj.userId}',${obj.dynamicId},'${obj.content}',${time},${type},'false')`
        await new Promise((resolve, reject) => {
            db.query(insertSql, (err, result) => {
                if (err) {
                    console.log(err)
                }
                else {
                    resolve('insert success')
                }
            })
        })
        var comment = {
            commentId: commentId,
            public_Time: time
        }
        ctx.body = comment
    }

})



// https://api.lzjlw.top:3030/residential/community_dynamic?type=3&dynamicId=
residential.delete('/community_dynamic', async (ctx) => {
    let obj = ctx.query
    if (obj.type == 3) {
        let deleteSql = `delete from community where type=${obj.type} and dynamicId=${obj.dynamicId}`
        let res = await new Promise((resolve, reject) => {
            db.query(deleteSql, (err, result) => {
                if (err) {
                    console.log(err)
                }
                else {
                    resolve('delete success')
                }
            })
        })
        ctx.body = res
    }
    else if (obj.type == 4) {
        let selectSql=`select userId from community_Comments where type=${obj.type} and commentId=${obj.commentId}`
        let userId=await new Promise((resolve, reject) => {
            db.query(selectSql, (err, result) => {
                if (err) {
                    console.log(err)
                }
                else {
                    resolve(result)
                }
            })
        })
        let deleteSql = `delete from community_Comments where type=${obj.type} and commentId=${obj.commentId}`
        await new Promise((resolve, reject) => {
            db.query(deleteSql, (err, result) => {
                if (err) {
                    console.log(err)
                }
                else {
                    resolve()
                }
            })
        })
        ctx.body = userId
    }

})


// 取消点赞
residential.delete('/community_Like',async (ctx)=>{
    let obj=ctx.request.body
    let type=ctx.query.type
    let deleteSql=`delete from community_Like where type=${type} and userId=${obj.userId} and from_Id=${obj.from_Id}`
    let res=await new Promise((resolve,reject)=>{
        db.query(deleteSql,(err,data)=>{
            if(err){
                throw err
            }else{
                resolve('delete success')
            }
        })
    })
    ctx.body=res
})

module.exports = residential